#include "stdafx.h"
#include "Pool.h"
#include <math.h>

CPool* CPool::m_sInstance = NULL;

CPool* CPool::GetInstance()
{
	if (m_sInstance == NULL)
	{
		m_sInstance = new CPool();
	}
	return m_sInstance;
}

void CPool::Destroy()
{
	DELETE_IF_NOT_NULL(m_sInstance);
}

CPool::CPool()
{
	for (int i = 0; i < SMALL_POOL_MAX/MEMPOOL_ALIGNMENT; i++)
	{
		m_pArenas[i] = new CArena(MEMPOOL_ALIGNMENT * ( 1 + i ), 1024, 1024 );
	}
}

CPool::~CPool()
{
	for (int i = 0; i < SMALL_POOL_MAX/MEMPOOL_ALIGNMENT; i++)
	{
		DELETE_IF_NOT_NULL( m_pArenas[i] );
	}
}

void* CPool::Alloc(size_t size)
{
    int index = InWhichArena(size);

	if (index == -1)
	{
		return ::operator new (size);
	}

	return m_pArenas[index]->Alloc();
}

void CPool::Free(void* p, size_t size)
{
	int index = InWhichArena(size);

	if (index == -1)
	{
		// the size is beyond the pool's capability, use the normal way to delete
		::operator delete (p);
		return;
	}

	m_pArenas[index]->Free(p);
}